<script lang="ts" setup>
import { componentMap } from "../componentMap";
import { FormSchema } from "../types";
import { isString } from "/@/utils/is";
import { useAttrs, computed } from "vue";
const attrs = useAttrs();
const props = defineProps<{
  schema: FormSchema;
  formProps;
  setFormModel: (k: string, v: any) => void;
}>();
const { component, field, label, rules = [] } = props.schema;

const labelIsVNode = computed(() => !isString(label));

const compAttr = computed(() => ({
  ...props.schema.componentProps,
}));

// 内容组件的双向绑定数据
const getModelValue = computed({
  get() {
    return props.formProps.model[field];
  },
  set(value) {
    props.setFormModel(field, value);
  },
});

const getBindValue = computed(() => {
  const value: any = {
    ...attrs,
    name: field,
    rules,
  };
  if (isString(label)) {
    value.label = label;
  }
  return value;
});
function renderComponent() {
  if (props.schema.render) {
    return props.schema.render;
  }
  return componentMap.get(component);
}
</script>

<template>
  <AFormItem v-bind="getBindValue">
    <template v-if="props.schema?.labelSlot" #label>
      <slot :name="props.schema?.labelSlot"></slot>
    </template>
    <slot
      :name="props.schema.componentProps?.slot"
      v-if="$slots[props.schema.componentProps?.slot]"
      :field="props.schema.field"
      :value="getModelValue"
    ></slot>
    <template v-else-if="['Switch', 'CheckBox'].includes(component)">
      <component
        v-model:checked="getModelValue"
        v-bind="compAttr"
        :is="renderComponent()"
      />
    </template>
    <template v-else-if="props.schema.component">
      <component
        v-model:value="getModelValue"
        v-bind="compAttr"
        :is="renderComponent()"
      />
    </template>
    <template v-else >
      <span :style="props.schema.style">{{ getModelValue }}</span>
    </template>
  </AFormItem>
</template>
